package com.ruoyi.web.controller.common;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.file.AliyunOssUtils;

/**
 * OSS文件上传控制器
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/oss")
public class OssController
{
    @Autowired
    private AliyunOssUtils aliyunOssUtils;

    /**
     * 上传单个文件到OSS
     */
    @PostMapping("/upload")
    public AjaxResult uploadFile(MultipartFile file) throws Exception
    {
        try
        {
            if (file == null || file.isEmpty())
            {
                return AjaxResult.error("上传文件不能为空");
            }

            // 上传文件到OSS
            String fileUrl = aliyunOssUtils.uploadFile(file);
            
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", fileUrl);
            ajax.put("fileName", file.getOriginalFilename());
            ajax.put("fileSize", file.getSize());
            ajax.put("message", "文件上传成功");
            
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error("文件上传失败：" + e.getMessage());
        }
    }

    /**
     * 批量上传文件到OSS
     */
    @PostMapping("/uploads")
    public AjaxResult uploadFiles(List<MultipartFile> files) throws Exception
    {
        try
        {
            if (files == null || files.isEmpty())
            {
                return AjaxResult.error("上传文件不能为空");
            }

            List<String> urls = new ArrayList<>();
            List<String> fileNames = new ArrayList<>();
            List<Long> fileSizes = new ArrayList<>();

            for (MultipartFile file : files)
            {
                if (file != null && !file.isEmpty())
                {
                    // 上传文件到OSS
                    String fileUrl = aliyunOssUtils.uploadFile(file);
                    urls.add(fileUrl);
                    fileNames.add(file.getOriginalFilename());
                    fileSizes.add(file.getSize());
                }
            }

            AjaxResult ajax = AjaxResult.success();
            ajax.put("urls", urls);
            ajax.put("fileNames", fileNames);
            ajax.put("fileSizes", fileSizes);
            ajax.put("message", "批量文件上传成功");
            
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error("批量文件上传失败：" + e.getMessage());
        }
    }

    /**
     * 删除OSS文件
     */
    @DeleteMapping("/delete")
    public AjaxResult deleteFile(@RequestParam String fileUrl)
    {
        try
        {
            if (fileUrl == null || fileUrl.trim().isEmpty())
            {
                return AjaxResult.error("文件URL不能为空");
            }

            // 从URL中提取文件名
            String fileName = aliyunOssUtils.extractFileNameFromUrl(fileUrl);
            if (fileName == null)
            {
                return AjaxResult.error("无效的文件URL");
            }

            // 删除文件
            boolean success = aliyunOssUtils.deleteFile(fileName);
            
            if (success)
            {
                return AjaxResult.success("文件删除成功");
            }
            else
            {
                return AjaxResult.error("文件删除失败");
            }
        }
        catch (Exception e)
        {
            return AjaxResult.error("文件删除失败：" + e.getMessage());
        }
    }

    /**
     * 检查文件是否存在
     */
    @GetMapping("/exists")
    public AjaxResult checkFileExists(@RequestParam String fileUrl)
    {
        try
        {
            if (fileUrl == null || fileUrl.trim().isEmpty())
            {
                return AjaxResult.error("文件URL不能为空");
            }

            // 从URL中提取文件名
            String fileName = aliyunOssUtils.extractFileNameFromUrl(fileUrl);
            if (fileName == null)
            {
                return AjaxResult.error("无效的文件URL");
            }

            // 检查文件是否存在
            boolean exists = aliyunOssUtils.doesObjectExist(fileName);
            
            AjaxResult ajax = AjaxResult.success();
            ajax.put("exists", exists);
            ajax.put("fileName", fileName);
            
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error("检查文件失败：" + e.getMessage());
        }
    }

    /**
     * 获取文件访问URL
     */
    @GetMapping("/url")
    public AjaxResult getFileUrl(@RequestParam String fileName)
    {
        try
        {
            if (fileName == null || fileName.trim().isEmpty())
            {
                return AjaxResult.error("文件名不能为空");
            }

            // 获取文件访问URL
            String fileUrl = aliyunOssUtils.getFileUrl(fileName);
            
            if (fileUrl != null)
            {
                AjaxResult ajax = AjaxResult.success();
                ajax.put("url", fileUrl);
                ajax.put("fileName", fileName);
                
                return ajax;
            }
            else
            {
                return AjaxResult.error("获取文件URL失败");
            }
        }
        catch (Exception e)
        {
            return AjaxResult.error("获取文件URL失败：" + e.getMessage());
        }
    }

    /**
     * 获取带签名的文件访问URL（临时访问）
     */
    @GetMapping("/signed-url")
    public AjaxResult getSignedUrl(@RequestParam String fileName, @RequestParam(defaultValue = "3600") long expireTime)
    {
        try
        {
            if (fileName == null || fileName.trim().isEmpty())
            {
                return AjaxResult.error("文件名不能为空");
            }

            // 获取带签名的文件访问URL
            String signedUrl = aliyunOssUtils.getSignedUrl(fileName, expireTime);
            
            if (signedUrl != null)
            {
                AjaxResult ajax = AjaxResult.success();
                ajax.put("url", signedUrl);
                ajax.put("fileName", fileName);
                ajax.put("expireTime", expireTime);
                
                return ajax;
            }
            else
            {
                return AjaxResult.error("获取签名URL失败");
            }
        }
        catch (Exception e)
        {
            return AjaxResult.error("获取签名URL失败：" + e.getMessage());
        }
    }
}
